﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using C1.Silverlight;
using System.IO;

namespace ControlExplorer
{
    public partial class Frame : UserControl
    {
        List<Storyboard> _storyboardsToRun = new List<Storyboard>();
        FrameworkElement _homePage = null;

        private const string LOAD_STORYBOARD_KEY = "LoadStoryboard";

        public Frame()
        {
#if (DEBUG)
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); 
#endif
            InitializeComponent();
        }

        #region ** ContentLoaded
        public void ContentLoaded(Uri currentUri, Uri targetUri)
        {
            _homePage = NavigationFrame.Content as FrameworkElement;
            _storyboardsToRun.Clear();
            if (targetUri == null)
            {
                return;
            }
            if (currentUri == null)
            {
                HandleStartFromEmptyPage(targetUri);
            }
            else if (!currentUri.OriginalString.Equals(targetUri.OriginalString))
            {
                if (IsSampleUri(currentUri) && IsSampleUri(targetUri))
                {
                    HandleSampleChange(currentUri, targetUri);
                }
                else if (IsHomeUri(currentUri) || (IsControlsUri(currentUri) && IsSampleUri(targetUri)))
                {
                    HandleLoadFromRight(currentUri, targetUri);
                }
                else if (IsSampleUri(currentUri) || (IsControlsUri(currentUri) && IsHomeUri(targetUri)))
                {
                    HandleLoadFromLeft(currentUri, targetUri);
                }
            }
            // run storyboards
            st_Completed(null, null);
            UpdateSocialButtons();
        }

        private void HandleStartFromEmptyPage(Uri targetUri)
        {
            Storyboard storyboard = Resources[LOAD_STORYBOARD_KEY] as Storyboard;
            if (storyboard != null)
            {
                _storyboardsToRun.Add(storyboard);
            }
            if (_homePage != null)
            {
                var contentStoryboard = _homePage.Resources[LOAD_STORYBOARD_KEY] as Storyboard;
                if (contentStoryboard != null)
                {
                    contentStoryboard.Begin();
                }
                AddPageFrameAnimation(false);
            }
        }

        private void HandleLoadFromLeft(Uri currentUri, Uri targetUri)
        {
            Storyboard storyboard = Resources["LoadFromLeftStoryboard"] as Storyboard;
            if (storyboard != null)
            {
                _storyboardsToRun.Add(storyboard);
            }
            if (_homePage != null)
            {
                AddPageFrameAnimation(false);
            }
        }

        private void HandleLoadFromRight(Uri currentUri, Uri targetUri)
        {
            Storyboard storyboard = Resources["LoadFromRightStoryboard"] as Storyboard;
            if (storyboard != null)
            {
                _storyboardsToRun.Add(storyboard);
            }
            if (_homePage != null)
            {
                AddPageFrameAnimation(false);
                if (IsSampleUri(targetUri))
                {
                    AddContentLoadedAnimation(LOAD_STORYBOARD_KEY);
                }
            }
        }

        private void HandleSampleChange(Uri currentUri, Uri targetUri)
        {
            if (_homePage != null)
            {
                AddPageFrameAnimation(true);
                string[] strs = currentUri.OriginalString.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
                if ( strs.Length > 0 && targetUri.OriginalString.StartsWith(strs[0], StringComparison.InvariantCulture))
                {
                     AddContentLoadedAnimation("ChangeSampleStoryboard");
                }
                else
                {
                    AddContentLoadedAnimation(LOAD_STORYBOARD_KEY);
                }
            }
        }

        private void AddPageFrameAnimation(bool skipToFill)
        {
            var pageFrame = VTreeHelper.GetChildOfType(_homePage, typeof(PageFrame)) as PageFrame;
            if (pageFrame != null && pageFrame.LoadStoryboard != null)
            {
                if (skipToFill)
                {
                    pageFrame.LoadStoryboard.Begin();
                    pageFrame.LoadStoryboard.SkipToFill();
                }
                else
                {
                    _storyboardsToRun.Add(pageFrame.LoadStoryboard);
                }
            }
        }
        private void AddContentLoadedAnimation(string key)
        {
            var contentStoryboard = _homePage.Resources[key] as Storyboard;
            if (contentStoryboard != null)
            {
                _storyboardsToRun.Add(contentStoryboard);
            }
        }

        void st_Completed(object sender, EventArgs e)
        {
            // run every next storyboard after the previous one has been completed
            Storyboard st = sender as Storyboard;
            if (st != null)
            {
                st.Completed -= new EventHandler(st_Completed);
            }
            if (_storyboardsToRun.Count > 0)
            {
                st = _storyboardsToRun[0];
                if (st != null)
                {
                    _storyboardsToRun.RemoveAt(0);
                    st.Completed += new EventHandler(st_Completed);
                    st.Begin();
                }
            }
        }

        // update Url in social buttons
        private void UpdateSocialButtons()
        {
            string url = HtmlPage.Document.DocumentUri.ToString();
            if (url.Contains("localhost"))
            {
                url = url.Replace("http://localhost", "");
                int index = url.IndexOf("/");
                if (index >= 0)
                {
                    url = "http://demo.componentone.com/silverlight/controlexplorer/" + url.Substring(index + 1);
                }
            }
            BTN_facebook.Url = url;
            BTN_facebook.Title = ((Page)NavigationFrame.Content).Title;
        }
        #endregion

        #region ** ContentUnloaded
        public void ContentUnloaded(Uri currentUri, Uri targetUri, Action completed)
        {
            _storyboardsToRun.Clear();
            SearchViewModel.Instance.ShowSearchList = false;

            Storyboard storyboard = null;
            if ((IsHomeUri(currentUri) && ! IsHomeUri(targetUri)) ||
                (IsControlsUri(currentUri) && IsSampleUri(targetUri)))
            {
                storyboard = Resources["UnloadToLeftStoryboard"] as Storyboard;
            }
            else if ((IsSampleUri(currentUri) && !IsSampleUri(targetUri)) ||
                (IsControlsUri(currentUri) && IsHomeUri(targetUri)))
            {
                storyboard = Resources["UnloadToRightStoryboard"] as Storyboard;
            }

            if (storyboard != null)
            {
                EventHandler c = null;
                c = (s, e) =>
                {
                    storyboard.Completed -= c;
                    completed();
                };
                storyboard.Completed += c;
                storyboard.Begin();
            }
            else
            {
                completed();
            }
        }
        #endregion

        #region ** Navigate
        public void Navigate(Uri targetUri, Uri currentUri)
        {
            try
            {
                NavigationFrame.Navigate(targetUri);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("** " + e.ToString());
                System.Diagnostics.Debug.WriteLine("** '" + targetUri.OriginalString + "'");
                ShowNavigationError(targetUri);
            }
        }

        public void ShowNavigationError(Uri targetUri)
        {
            C1MessageBox.Show(targetUri.OriginalString + "\r\n" + new System.IO.FileNotFoundException().Message,
               "Navigation Error", C1MessageBoxIcon.Warning,
               new Action<MessageBoxResult>((r) =>
               {
                   // restores current content 
                   Storyboard storyboard = null;
                   double translate = ((CompositeTransform)NavigationFrame.RenderTransform).TranslateX;
                   if (translate > 0)
                   {
                       storyboard = Resources["LoadFromRightStoryboard"] as Storyboard;
                   }
                   else if (translate < 0)
                   {
                       storyboard = Resources["LoadFromLeftStoryboard"] as Storyboard;
                   }
                   if (storyboard != null)
                   {
                       storyboard.Begin();
                   }
               }));
        }


        private void BTN_download_Click(object sender, RoutedEventArgs e)
        {
            HtmlPage.Window.Navigate(new Uri("http://www.componentone.com/StudioSilverlight/Download/"), "_new");
        }

        private void Home_Clicked(object sender, MouseButtonEventArgs e)
        {
            // empty string will use MappedUri defined in xaml
            NavigationFrame.Navigate(new Uri("", UriKind.Relative));
        }
        #endregion

        private bool IsHomeUri(Uri currentUri)
        {
            return currentUri.OriginalString.Contains(PlatformUtils.AdjustPlatformXamlName("HomePage.xaml", false));
        }

        private bool IsControlsUri(Uri currentUri)
        {
            return currentUri.OriginalString.Contains(PlatformUtils.AdjustPlatformXamlName("ControlsPage.xaml", false));
        }

        private bool IsSampleUri(Uri currentUri)
        {
            return !IsHomeUri(currentUri) && !IsControlsUri(currentUri);
        }
    }
}
